import { baseURL } from "./http";
// import store from '@/store'
import { useUserInfoStore } from "@/stores/user-info";
import va from "./rules";
import { computed } from "vue";

// 获取 store 的实例
const userKey = computed(() => useUserInfoStore().userKey);
// 本地缓存，当前采用 localStorage
const _dateKey = "DATE::";
const _jsonKey = "JSON::";
const _stringKey = "string";
export function localCacher(key, value) {
  if (key) {
    if (value == undefined) {
      value = localStorage.getItem(key);
      if (value) {
        if (value.substr(0, _dateKey.length) == _dateKey) {
          value = new Date(JSON.parse(value.substr(_dateKey.length)));
        } else if (value.substr(0, _jsonKey.length) == _jsonKey) {
          value = JSON.parse(value.substr(_jsonKey.length));
        }
      }
      return value;
    } else {
      if (typeof value !== _stringKey) {
        if (value instanceof Date) {
          value = _dateKey + JSON.stringify(value);
        } else {
          value = _jsonKey + JSON.stringify(value);
        }
      }
      localStorage.setItem(key, value);
    }
  }
}

// 用户信息存取
export function userInfor(value, route) {
  if (value == undefined) {
    return localCacher(userKey.value);
  } else {
    localCacher(userKey.value, value);
    // if (route) {
    //   store.commit(store.state.routesKey, value);
    // }
  }
}

// 最后操作
const _lastOperKey = "LSTPRKY";
const _timeout = 60 * 60 * 1000;
export function lastOper(start) {
  if (start) {
    localCacher(_lastOperKey, new Date());
  } else {
    let expire = true;
    let time = localCacher(_lastOperKey);
    if (time && time instanceof Date) {
      let now = new Date();
      if (now - time < _timeout) {
        localCacher(_lastOperKey, now);
        expire = false;
      }
    }
    if (expire) {
      // userInfor("", true);
      window.location.reload();
    }
  }
}

// 常用验证
const _vr = {
  requr: [va.required()],
  rNumber: [va.required(), va.number(0)],
  rFloat: [va.required(), va.numberGreater(0.0000000001)],

  rCode: [va.required(), va.length(0, 30), va.code()], // 编码
  rName: [va.required(), va.length(0, 20), va.cnOrEnAndNum()], // 名称
  rTitle: [va.required(), va.length(0, 50), va.cnOrEnAndNum()], // 标题
  rType: [va.required(), va.length(0, 20), va.cnOrEnAndNum()], // 类型
  rMode: [va.required(), va.length(0, 20), va.cnOrEnAndNum()], // 型号
  rUnit: [va.required(), va.length(0, 10), va.cnOrEnAndNum()], // 单位
  rMix: [va.required(), va.length(0, 20), va.cnEnNumPun()], // 名称
  rTel: [va.required(), va.tel()],
  rRemark: [va.required(), va.length(0, 50)],

  rDay180: [va.required(), va.number(1, 180)],
  rScore: [va.required(), va.number(1, 100)],

  rRate: [va.required(), va.number(1, 5, "最少一星")],
  rResult: (max) => {
    return [va.required(), va.number(0, max)];
  },
  renOrNum: [va.required(), va.enOrNum()],

  code: [va.length(0, 20), va.code()], // 编码
  name: [va.length(0, 20), va.cnOrEnAndNum()], // 名称
  title: [va.length(0, 50), va.cnOrEnAndNum()], // 标题
  type: [va.length(0, 20), va.cnOrEnAndNum()], // 类型
  mode: [va.length(0, 20), va.cnOrEnAndNum()], // 型号
  idCode: [va.idCode()], // 身份证号码
  tel: [va.tel()],
  email: [va.email()],
  wx: [va.wx()], // 微信
  qq: [va.qq()], // QQ
  url: [va.url()],
  enOrNum: [va.enOrNum()],

  remark: [va.length(0, 50)],
  menu: [va.required(), va.menu()],
};

// 确认配置
const _confirm = {
  confirmButtonText: "确定",
  cancelButtonText: "取消",
  type: "warning",
};

const install = (app) => {
  // 本地缓存
  app.config.globalProperties.$localCacher = localCacher;
  // 用户信息
  app.config.globalProperties.$userInfor = userInfor;
  // 最后操作
  app.config.globalProperties.$lastOper = lastOper;
  // 常用验证
  app.config.globalProperties.$vr = _vr;

  // 成功消息
  app.config.globalProperties.$messageSuccess = function (message) {
    this.$message({
      showClose: true,
      message: message,
      type: "success",
      duration: 1000,
    });
  };
  // 警告消息
  app.config.globalProperties.$messageWarning = function (message) {
    this.$message({
      showClose: true,
      message: message,
      type: "warning",
      duration: 2500,
    });
  };
  // 错误消息
  app.config.globalProperties.$messageError = function (message) {
    this.$message({
      showClose: true,
      message: message,
      type: "error",
      duration: 2500,
    });
  };
  // 确认消息
  app.config.globalProperties.$messageConfirm = function (message, ok, tip) {
    this.$confirm(message, tip || "提示", _confirm)
      .then(() => {
        if (ok) {
          ok();
        }
      })
      .catch((err) => {
        if (err != "cancel") {
          this.$messageError(err);
        }
      });
  };

  // 清空对象属性
  app.config.globalProperties.$propsEmpty = function (obj) {
    if (obj) {
      if (Array.isArray(obj)) {
        if (obj.length) {
          obj.splice(0, obj.length);
        }
      } else if (obj instanceof Date) {
        obj = null;
      } else if (typeof obj == "object") {
        for (const key in obj) {
          if (Object.hasOwnProperty.call(obj, key)) {
            let val = this.$propsEmpty(obj[key]);
            if (obj[key] instanceof Date || typeof obj[key] != "object") {
              obj[key] = val;
            }
          }
        }
      } else if (typeof obj == "boolean") {
        obj = false;
      } else if (typeof obj == "number") {
        obj = 0;
      } else if (typeof obj == "string") {
        obj = "";
      } else {
        obj = null;
      }
    }
    return obj;
  };
  // 复制对象属性
  app.config.globalProperties.$propsCopy = function (to, from) {
    if (to && typeof to == "object" && from && typeof from == "object") {
      for (const key in to) {
        if (
          Object.hasOwnProperty.call(to, key) &&
          Object.hasOwnProperty.call(from, key)
        ) {
          to[key] = from[key];
        }
      }
    }
  };

  // 常新链接
  app.config.globalProperties.$freshUrl = function (url) {
    if (url) {
      return url + "?v=" + Math.random();
    }
  };
  // 服务器链接
  app.config.globalProperties.$serverUrl = function (url) {
    if (url) {
      return baseURL + url;
    }
  };
  // 提交文件检查
  app.config.globalProperties.$checkFile = function (file, accept, max) {
    if (file) {
      if (file.name) {
        let i = file.name.lastIndexOf(".");
        if (i > 0) {
          let x = file.name.substr(i).toLowerCase();
          if (x) {
            if (accept) {
              if (accept != "*.*") {
                const accepts = accept.split(",");
                if (
                  accepts.every((e) => {
                    return e != x;
                  })
                ) {
                  this.$messageError("文件类型不支持，请重新选择文件");
                  return false;
                }
              }
              if (file.size > max * 1024 * 1024) {
                this.$messageError("文件大小应在 " + max + "MB 以内");
                return false;
              } else {
                return true;
              }
            }
            this.$messageError("文件类型限制，请重新选择文件");
            return false;
          }
        }
        this.$messageError("文件类型有误，请重新选择文件");
        return false;
      }
    }
    this.$messageError("请选择要上传的文件");
    return false;
  };

  // 日期格式化
  app.config.globalProperties.$week = function (date) {
    if (date == null) {
      date = new Date();
    }
    let day = 0;
    if (date instanceof Date) {
      day = date.getDay();
    } else if (typeof date == "number") {
      day = date % 7;
    } else {
      return date;
    }
    return "日一二三四五六".substr(day, 1);
  };
  // 日期格式化
  app.config.globalProperties.$yyyy_MM_dd = function (date) {
    return (date || new Date()).format("yyyy-MM-dd");
  };
  // 日期格式化
  app.config.globalProperties.$yyyy_MM_dd_ = function (date) {
    return (date || new Date()).format("yyyy年MM月dd日");
  };
  // 时间格式化
  app.config.globalProperties.$yyyy_MM_dd_HH_mm = function (date) {
    return (date || new Date()).format("yyyy-MM-dd hh:mm");
  };
  // 时间格式化
  app.config.globalProperties.$yyyy_MM_dd_HH_mm_ss = function (date) {
    return (date || new Date()).format("yyyy-MM-dd hh:mm:ss");
  };
};
export { install as default };
